<?php

namespace app\controller;


use app\BaseController;
use app\dto\PageDto;
use app\dto\UserDto;
use app\model\Menu;
use app\model\ModifyQuery;
use app\model\User;
use app\model\BaseQuery;
use app\model\WenZhang;
use app\Request;
use app\service\RedisService;
use app\utils\Md5;
use app\utils\Utils;
use app\validate\WenzhangValidate;
use http\Message\Body;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;


class RoleController extends BaseController
{


    function pageList(Request $request)
    {
        $menuDto = $request->all();
        $query = BaseQuery::build(Menu::class);
        if (Utils::isNotNull($menuDto, 'id')) {
            $query->where('id', $menuDto['id']);
        }
        if (Utils::isNotNull($menuDto, 'parentId')) {
            $query->where('parentId', $menuDto['parentId']);
        }
        if (Utils::isNotNull($menuDto, 'name')) {
            $query->where('name', 'like', "{$menuDto['name']}%");
        }

        $resultlist = $query->select();
        $total = $query->count();
        return json([
            "data" => $resultlist,
            "count" => $total
        ]);
    }

    function getItem(Request $request)
    {
        $id = $request->get("id");
        $parentId = $request->get("parentId");
        $query = BaseQuery::build(Menu::class);
        if (isset($id)) {
            $query->where('id', $id);
        }
        if (isset($parentId)) {
            $query->where('$parentId', $parentId);
        }
        $resultlist = $query->find();
        return Utils::ok($resultlist);
    }

    function add(Request $request)
    {
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("没有参数");
        }
        unset($params['id']);
        if (Utils::isNullPlus($params, 'name')) {
            return Utils::failRes("没有参数,name");
        }
        $id = Menu::save($params);
        return utils::ok($id);
    }

    function update(Request $request)
    {
        $params = $request->all();
        /*校验 */
        if (Utils::isNullPlus($params, 'id')) {
            return Utils::failRes("id 必填");
        }
        /*查询是否存在*/
        $query = BaseQuery::build(Menu::class);
        $one = $query->where("id", $params['id'])->find();
        if (Utils::isNullPlus($one, 'id')) {
            return Utils::failRes("id:{$params['id']} 没有找到数据");
        }
        $modifyQuery = ModifyQuery::build(Menu::class);
        $resultint = $modifyQuery->update($params, [
            'id' => $params['id']
        ]);

        return Utils::ok($resultint);
    }

    function del(Request $request)
    {
        $id = $request->post("id");
        if (!isset($id)) {
            return Utils::failRes("id参数不能为空");
        }
        $userone = User::find($id);

        if (Utils::isNull($userone)) {
            return Utils::failRes("id: {$id} 找不到数据");
        }

        $result = BaseQuery::build(Menu::class)->where("id", $id)
            ->useSoftDelete('delete_time', Utils::dateyyyymmddhhmmss(time()))
            ->delete();
        return Utils::ok($result);
    }


    function bindMenus(Request $request)
    {
        /*
         * roleId
         * menuIds
         * */
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("没有参数");
        }
        if (Utils::isNullPlus($params, 'roleId')) {
            return Utils::failRes("需要参数，roleId");
        }
        if (Utils::isNullPlus($params, 'menuIds')) {
            return Utils::failRes("需要参数，menuIds");
        }
        $modifyQuery = ModifyQuery::build('tb_menu_role_ref', true);
        $addArray = [];
        foreach ($params['menuIds'] as $menuId) {
            array_push($addArray, [
                Utils::toLine("menuId") => $menuId,
                Utils::toLine("roleId") => $params['roleId']
            ]);
        }
        $addResult = $modifyQuery->insertAll($addArray);
        return Utils::ok($addResult);

    }

    function getMenus(Request $request)
    {
        $params = $request->all();
        /*获取当前登录人*/
        $userId = Utils::getUserInfoId($request);
        $parentId = $params['parentId'] ?? 0;
        if (empty($userId)) {
            return Utils::failRes("没有获取到登录信息");
        }
        /*使用userid 查询roleids*/
        $queryroles = BaseQuery::build("tb_user_role_rel",true);
        $roleResultIds = Utils::toHumpForArray($queryroles->where("user_id", $userId)->select()->toArray());
        if (empty($roleResultIds)) {
            return Utils::ok([]);
        }
        $roleIds = Utils::map($roleResultIds, function ($item) {
            return $item['roleId'];
        });
        if(empty($roleIds)){
            return Utils::ok([]);
        }

        $roleidstr = implode(',', $roleIds);



        /*使用roleid parentid 查询 menu*/
      $resultMeneRoleRefs=  Db::query("
 select * from tb_menu_role_ref mrf
            left join  tb_menu menu   on mrf.menu_id=menu.id 
where  mrf.role_id in ($roleidstr) 
and menu.parent_id=$parentId
            ");

        $resultMeneRoleRefs = Utils::toHumpForArray($resultMeneRoleRefs);

        $menuArray = [];
        foreach ($resultMeneRoleRefs as $refItem){
            $one=Menu::where("id",$refItem['menuId'])->find()->toArray();
            if(Utils::isNotNull($one,'id')){
                array_push($menuArray, $one);
            }
        }
        return Utils::ok($menuArray);

    }



    /* 用户绑定多个角色*/
    function bindUser(Request $request)
    {
        $params = $request->all();
        if (!isset($params)) {
            return Utils::failRes("沒有參數");
        }
        $userId = $params['userId'];
        if (empty($userId)) {
            return Utils::failRes("参数 userId 必填");
        }
        $roleIds = $params['roleIds'];
        if (empty($roleIds)) {
            return Utils::failRes("参数 roleIds 必填");
        }
        $query = ModifyQuery::build("tb_user_role_rel");
        $insertArray = [];
        foreach ($roleIds as $roleId) {
            array_push($insertArray, [
                "role_id" => $roleId,
                "user_id" => $userId
            ]);
        }
        $result = $query->insertAll($roleIds);
        return Utils::ok($result);
    }


}